import cocos, pyglet
from cocos.director import director

from config import current as conf

class MapEditorLayer(cocos.layer.Layer):
    """Allows the solid parts of the map to be edited"""
    def __init__(self, state, gamegrid):
        super(MapEditorLayer, self).__init__()
        self.state = state
        self.gamegrid = gamegrid

        self.editing = False
        
        self.markers = {}

    def new_marker(self, cell):
        x,y = self.gamegrid.cell_to_pixel(cell)
        return cocos.text.Label("X",
                        font_name=conf.title_font, font_size=32,
                        color=(100,0,0,150), x=x, y=y,
                        anchor_x='center', anchor_y='center')

    is_event_handler = True
    def on_key_press (self, key, modifiers):
        if key == pyglet.window.key.E and (modifiers & pyglet.window.key.MOD_ACCEL):
            if self.editing:
                self.editing = False
                for marker in self.markers.values():
                    self.remove(marker)
                self.markers = {}
                self.parent.messages.show("leaving edit mode...")
            else:
                self.editing = True
                self.parent.messages.show("entering edit mode, <shift>+drag to delete, <cmd>+drag to add...")
                for cell in self.state.solid_pts:
                    self.markers[cell] = self.new_marker(cell)
                    self.add(self.markers[cell], z=2)

    def on_mouse_press(self, sx, sy, buttons, modifiers):
        if self.editing and (buttons & pyglet.window.mouse.RIGHT):
            x, y = director.get_virtual_coordinates(sx,sy)
            cell = self.gamegrid.pixel_to_cell((x,y))
            print cell
        return self.on_mouse_drag(sx, sy, 0, 0, buttons, modifiers)

    def on_mouse_drag(self, sx, sy, dx, dy, buttons, modifiers):
        if self.editing:
            x, y = director.get_virtual_coordinates(sx,sy)
            cell = self.gamegrid.pixel_to_cell((x,y))
            if (buttons & pyglet.window.mouse.LEFT) and (modifiers & pyglet.window.key.MOD_SHIFT):
                if cell in self.state.solid_pts:
                    self.remove(self.markers[cell])
                    del self.markers[cell]
                    self.state.solid_pts.remove(cell)
            elif (buttons & pyglet.window.mouse.LEFT) and (modifiers & pyglet.window.key.MOD_ACCEL):
                if not cell in self.state.solid_pts:
                    self.state.solid_pts.add(cell)
                    self.markers[cell] = self.new_marker(cell)
                    self.add(self.markers[cell], z=2)
            return True
        return False
